#!/usr/bin/python3
import hashlib
import requests
import json
import uuid

hostIP = "http://127.0.0.1:18866"
username = "IOT2021"
password = "Mima2021@)@!"
token = ""
headers={}

def login():
    sha256=hashlib.sha256()
    sha256.update(password.encode('utf-8'))
    body={"un":username,"pd":sha256.hexdigest()}
    headers['Content-Type']='application/json'
    #header={"Content-Type":"application/x-www-form-urlencoded","X-Requested-With":"XMLHttpRequest"}
    resp=requests.post(hostIP + "/api/su/login",data=json.dumps(body),headers=headers)
    print(resp.text)
    jresult = json.loads(resp.text)
    token = jresult['result']['token']
    print("_________token_____________")
    print(token)
    headers['api_token'] = token

def update(prefix,info):
    print("---------update------------" + prefix)
    resp = requests.put(hostIP + "/api/cfg/"+prefix,data=json.dumps(info),headers=headers)
    print(resp.text)
    jresp = json.loads(resp.text)
    jresult = jresp['result']
    print(jresult)

def deleteByID(prefix,id):
    resp = requests.delete(hostIP + "/api/cfg/"+prefix+'/' + id,headers=headers)
    print("---------deletebyid------------" + prefix + "id " + id)
    print(resp.text)
    jresp = json.loads(resp.text)
    jresult = jresp['result']
    print(jresult)

def getAll(prefix):
    resp = requests.get(hostIP + "/api/cfg/"+prefix+'/',headers=headers)
    print("---------getall------------" + prefix)
    print(resp.text)
    jresp = json.loads(resp.text)
    jresult = jresp['result']
    print(jresult)

def getByID(prefix,id):
    resp = requests.get(hostIP + "/api/cfg/"+prefix+'/' + id,headers=headers)
    print("---------getbyid------------" + prefix + "id " + id)
    print(resp.text)
    jresp = json.loads(resp.text)
    jresult = jresp['result']
    print(jresult)